package domain;

import java.awt.Point;
import java.util.ArrayList;

public class Tablero {

	private ArrayList<ArrayList<CuadradoEnTablero>> elems;
	private Pista pista;
	private int size;
	
	public Tablero (int size, Pista pista){
		//suponer que el tablero va a tener todos CuadradoEnTablero
		elems = new ArrayList<ArrayList<CuadradoEnTablero>> (size);
		this.pista = pista;
		this.size = size;
		
		for (int i = 0; i<=size; i++){
			elems.add(i, this.cuadradoArray(size) );
		}
		initContorno();
		initObjetos();
		setElem(new Tesoro(pista, pista.getTeam(1)), new Point(6,5));
		setElem(new Tesoro(pista, pista.getTeam(2)), new Point(7,5));
	}

	private ArrayList<CuadradoEnTablero> cuadradoArray(int size) {
		ArrayList<CuadradoEnTablero> array = new ArrayList<CuadradoEnTablero> (size);
		for (int i = 0; i <= size; i++){
			array.add(new CuadradoEnTablero());
		}
		return array;
	}

	private void initObjetos() {
		lineaObjetos (new Point(5, 1), 6, new Norte());
		lineaObjetos (new Point(10, 5), 6, new Sur());
	}

	private void initContorno() {
		int max = elems.size() -1;

		lineaObjetos (new Point(), max, new Este());
		lineaObjetos (new Point(), max, new Norte());
		lineaObjetos (new Point(0, max), max, new Este());
		lineaObjetos (new Point(max, 0), max, new Norte());
		
	}

	private void lineaObjetos(Point point, int veces, Direccion dir) {
		Point cp = point;
		int left = veces;
		while (left > 0){
			setElem(new Obstaculo(), cp);
			cp = dir.getNext(cp);
			left--;
		}
	}

	synchronized  public ObjetoEnTablero getElem(Point p){
		return elems.get(p.x).get(p.y).getElem();
	}
	synchronized public void setElem (ObjetoEnTablero elem, Point p){
		elems.get(p.x).get(p.y).setElem(elem);
		elem.setPosicion(p);
	}
	synchronized public void moverElem (Point orig, Point destino){
		ObjetoEnTablero origElem, destElem;
		origElem = getElem(orig);
		destElem = getElem(destino);
		
		origElem.setPosicion(destino);
		destElem.setPosicion(orig);
		
		setElem (origElem, destino);
		setElem (destElem, orig);
	}
	public CuadradoEnTablero getCuadrado (Point p){
		return elems.get(p.x).get(p.y);
	}
	public void ubicarEnPosicionLibre(Auto auto) {
		Point currentPoint = new Point(0, 0);
		int maxCoord = elems.size();
		boolean ubicado = false;
		
		while (currentPoint.y < maxCoord & !ubicado){
			
			while (currentPoint.x < maxCoord & !ubicado){
				if (getCuadrado(currentPoint).estaVacio()){
					this.setElem(auto, new Point(currentPoint.x, currentPoint.y));
					ubicado = true;
				}

				currentPoint.move(currentPoint.x+1, currentPoint.y);
			}
			currentPoint.move(0, currentPoint.y+1);
		}
		
	}

	public int getSize() {
		return size;
	}

	public boolean fueraDeTablero(Point poss) {
		return poss.x >= elems.size() | poss.y >= elems.size();
	}
}
